package com.itheima.design.mode.observer.event;

import com.google.common.collect.Maps;
import com.itheima.design.mode.observer.listener.EventListener;
import com.itheima.design.mode.observer.service.LotteryResult;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 事件管理
 */
public class EventManager {

    Map<Enum<EventType>, List<EventListener>> listeners = Maps.newHashMap();

    public EventManager(Enum<EventType>... operations) {
        for (Enum<EventType> operation: operations){
            this.listeners.put(operation,new ArrayList<>());
        }
    }

    public enum EventType{
        MQ,Message
    }

    /**
     * 订阅
     * @param type
     * @param listener
     */
    public void subscribe(Enum<EventType> type,EventListener listener){
        List<EventListener> users = listeners.get(type);
        users.add(listener);
    }

    /**
     * 取消订阅
     * @param type
     * @param listener
     */
    public void unSubscribe(Enum<EventType> type,EventListener listener){
        List<EventListener> users = listeners.get(type);
        users.remove(listener);
    }

    /**
     * 通知
     * @param type
     * @param result
     */
    public void notify(Enum<EventType> type, LotteryResult result){
        List<EventListener> users = listeners.get(type);
        for (EventListener listener: users){
            listener.onEvent(result);
        }
    }
}
